package com.huxiu.yd;

import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.responses.BaseResponse;
import com.huxiu.yd.net.responses.ProfileResponse;
import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.Global;
import com.huxiu.yd.utils.Settings;
import com.huxiu.yd.utils.Utils;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;


public class RegisterActivity2 extends AuthenticatorActivity implements OnClickListener {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_image)
    ImageView rightImage;

    @InjectView(R.id.right_text)
    TextView rightText;

    @InjectView(R.id.username_edit)
    EditText usernameEdit;

    @InjectView(R.id.password_edit)
    EditText passwordEdit;

    @InjectView(R.id.log_in_button)
    Button registerButton;

    private String mobile;

    private String verifyCode;

    private boolean isFindPassword = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register2);
        isFindPassword = getIntent().getBooleanExtra("forget_password", false);
        ButterKnife.inject(this);
        back.setOnClickListener(this);
        if (isFindPassword) {
            title.setText(R.string.find_password);
            usernameEdit.setHint(R.string.set_new_password);
            usernameEdit.setInputType(InputType.TYPE_CLASS_TEXT | InputType
                    .TYPE_TEXT_VARIATION_PASSWORD);
            passwordEdit.setHint(R.string.confirm_password);
            passwordEdit.setInputType(InputType.TYPE_CLASS_TEXT | InputType
                    .TYPE_TEXT_VARIATION_PASSWORD);
            registerButton.setText(R.string.confirm);
        } else {
            title.setText(R.string.register);
        }
        rightImage.setVisibility(View.GONE);
        rightText.setVisibility(View.GONE);
        registerButton.setOnClickListener(this);
        mobile = getIntent().getStringExtra(Constants.MOBILE_KEY);
        verifyCode = getIntent().getStringExtra(Constants.VERIFY_CODE_KEY);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.log_in_button:
                if (isFindPassword) {
                    if (isValidPassword(usernameEdit) && isValidPassword(passwordEdit) &&
                            isSamePassword()) {
                        doUpdatePassword();
                    }
                } else {
                    if (TextUtils.isEmpty(usernameEdit.getText().toString())) {
                        Utils.showToast(R.string.pls_input_username);
                    } else if (!isValidLengthUsername(usernameEdit)) {
                        Utils.showToast(R.string.username_too_short);
                    } else if (TextUtils.isEmpty(passwordEdit.getText().toString())) {
                        Utils.showToast(R.string.pls_input_password);
                    } else if (!isValidPassword(passwordEdit)) {
                        Utils.showToast(R.string.invalid_password_length);
                    } else {
                        doRegister();
                    }
                }
                break;
        }
    }

    static CharsetEncoder ASCII_ENCODER = Charset.forName("US-ASCII").newEncoder();

    private boolean isValidLengthUsername(EditText editText) {
        String username = editText.getText().toString();
        int sum = 0;
        if (TextUtils.isEmpty(username)) {
            return false;
        }
        for (int i = 0; i < username.length(); i++) {
            char c = username.charAt(i);
            sum += ASCII_ENCODER.canEncode(c) ? 1 : 2;
        }
        return 4 <= sum && sum <= 12;
    }


    private boolean isValidPassword(EditText editText) {
        String password = editText.getText().toString();
        if (password.length() >= 6 && password.length() <= 16) {
            return true;
        } else {
            Utils.showToast(R.string.invalid_password_length);
            return false;
        }
    }

    private boolean isSamePassword() {
        if (passwordEdit.getText().toString().contentEquals(usernameEdit.getText
                ().toString())) {
            return true;
        } else {
            Utils.showToast(R.string.different_password_confirm);
            return false;
        }
    }

    private void doUpdatePassword() {
        Map<String, String> params = new LinkedHashMap<>();
        params.put("mobile", mobile);
        params.put("act", "up_password");
        params.put("captcha", verifyCode);
        params.put("password", Utils.getEncryptedPassword(passwordEdit.getText().toString()));
        GsonRequest<BaseResponse> request = new GsonRequest<>(NetworkConstants.MEMBER_URL,
                Method.POST, BaseResponse.class, false, params, new Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                dismissProgress();
                if (response.isSuccess()) {
                    setResult(RESULT_OK);
                    finish();
                }
                Utils.showToast(response.msg);
            }
        }, mErrorListener);
        showProgress();
        mQueue.add(request);
//        mQueue.start();
    }

    private void doRegister() {
        Map<String, String> params = new LinkedHashMap<>();
        params.put("username", usernameEdit.getText().toString());
        params.put("password", Utils.getEncryptedPassword(passwordEdit.getText().toString()));
        params.put("mobile", mobile);
        params.put("act", "user_reg");
        params.put("captcha", verifyCode);
        GsonRequest<ProfileResponse> request = new GsonRequest<>(NetworkConstants.MEMBER_URL,
                Method.POST, ProfileResponse.class, false, params, new Listener<ProfileResponse>() {
            @Override
            public void onResponse(ProfileResponse response) {
                dismissProgress();
                if (response.isSuccess()) {
                    Settings.saveProfile(response.data.toString());
                    Global.setUser(response.data);
                    setResult(RESULT_OK);
                    LocalBroadcastManager.getInstance(App.getInstance())
                            .sendBroadcast(new Intent(Constants.INTENT_USER_LOGGED_IN));
                    finish();
                } else {
                    Utils.showToast(response.msg);
                }
            }
        }, mErrorListener);
        showProgress();
        mQueue.add(request);
//        mQueue.start();
    }
}
